import axios, { AxiosInstance } from 'axios'
import { Store } from 'vuex'
import { RootStateOptions } from '@/store/state'
import qs from 'qs'

const createApi = (store: Store<RootStateOptions>): AxiosInstance => {
  console.log(store.state)
  const config = axios.create({
    baseURL: '/api', // 客户端请求需要跨域代理，设置代理路径前
    headers: {
      accept: '*/*',
      'content-type': 'application/x-www-form-urlencoded'
    },
    timeout: 15000,
    withCredentials: false
  })
  // 请求拦截
  config.interceptors.request.use(config => {
    if (config.url === '/v2/carts') {
      config.headers['Cache-Control'] = 'no-cache'
    }
    config.headers.abb = 'en'
    config.headers['patpat-platform'] = 'wap'
    config.headers.token = 'guest'
    if (config.method && (config.method.toLocaleLowerCase() === 'post' || config.method.toLocaleLowerCase() === 'put' || config.method.toLocaleLowerCase() === 'delete')) {
      if (Object.prototype.toString.call(config.data) !== '[object FormData]') {
        config.data = qs.stringify(config.data)
      }
    }
    return config
  })

  config.interceptors.response.use(response => {
    // let data
    // IE9时response.data是undefined，因此需要使用response.request.responseText(Stringify后的字符串)
    // if (response.data === undefined) {
    //   data = JSON.parse(response.request.responseText)
    // } else {
    //   data = response.data
    // }
    const resError = {
      ...new Error('error'),
      status: response.status
    }

    switch (response.status) {
      case 200:
        return response
      case 403:
        console.log('403 response', response)
        return Promise.reject(resError) // location.href刷新页面存在延迟，会导致一些请求方法的then方法的resolve回调代码执行
      default:
        console.log('interceptors.response default', response)
        return Promise.reject(resError)
    }
  }, error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = 'Bad Request'
          break
        case 403:
          error.message = 'Forbidden'
          break
        case 404:
          error.message = 'Not Found'
          break
        case 500:
          error.message = 'Internal Server Error'
          break
        default:
          error.message = `Connection error ${error.status}`
      }
    } else {
      if (error.message.indexOf('timeout') !== -1) {
        error = { status: 503, message: 'The network connection is temporarily unavailable. Please refresh the page and try again.', time_out: true }
      } else if (error.message.indexOf('canceled') !== -1) {
        error.status = 400
      }
    }
    return Promise.reject(error)
  })
  return config
}
export default createApi
